package com.calvin.lingting;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.calvin.lib.annotation.Notice;
import com.calvin.lib.json.JSONObject;
import com.calvin.lib.notification.NotificationCenter;
import com.calvin.lingting.config.AppConfig;
import com.calvin.lingting.config.LrtsConfig;
import com.calvin.lingting.config.NTConfig;
import com.calvin.lingting.service.SerializationCenter;

import java.util.Timer;
import java.util.TimerTask;

public class MediaPlayService extends Service implements OnPreparedListener, MediaPlayer.OnCompletionListener {
    static MediaPlayService mInstance = null;
    JSONObject mBookInfo;
    MediaPlayer mMediaPlayer;
    Integer mCurrentIndex;
    Timer mTimer;
    boolean mIsPrepare = false;
    int mPos = 0;

    public MediaPlayService() {
        mInstance = this;
        NotificationCenter.shared().scanNotice(this);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mTimer = new Timer();
        startCalcTime();
    }

    public static MediaPlayService shared() {
        return mInstance;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (isPlay()) {
            NotificationCenter.shared().postNotice(NTConfig.NT_CHANGE_MEDIA_INFO, 0, mBookInfo, mCurrentIndex);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mTimer.cancel();
        mMediaPlayer.stop();
        mMediaPlayer.release();
        super.onDestroy();
    }

    @Notice(NTConfig.NT_MD_PLAY)
    public void onNtPlay(Object... argv) {
        mIsPrepare = false;
        mBookInfo = (JSONObject) argv[0];
        mCurrentIndex = (Integer) argv[1];
        if (argv.length > 2) {
            mPos = (Integer) argv[2];
        }
        String url;
        if (mBookInfo.containsKey(LrtsConfig.K_DOWNDLOAD) && mBookInfo.getJSONArray(LrtsConfig.K_DOWNDLOAD).contains(mCurrentIndex)) {
            String path = Environment.getExternalStoragePublicDirectory(AppConfig.SD_BOOK).getPath();
            String name = mBookInfo.getStringValue(LrtsConfig.K_NAME);
            url = String.format("%s/%s/%s.mp3", path, name, mCurrentIndex);
        } else {
            url = mBookInfo.getJSONObject(LrtsConfig.K_CHAPTER_LIST).getStringValue(mCurrentIndex.toString());
        }
        System.out.println(url);
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(this, Uri.parse(url));
            mMediaPlayer.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
        SerializationCenter.shared().addRecordBookList(mBookInfo);
        NotificationCenter.shared().postNotice(NTConfig.NT_CHANGE_MEDIA_INFO, 0, mBookInfo, mCurrentIndex);
    }

    @Notice(NTConfig.NT_MD_PAUSE)
    public void onNtPause(Object... argv) {
        if (mBookInfo != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            NotificationCenter.shared().postNotice(NTConfig.NT_CHANGE_MEDIA_INFO, 2);
        } else {
            Toast.makeText(this, R.string.s_choice_book, Toast.LENGTH_SHORT).show();
        }
    }

    @Notice(NTConfig.NT_MD_RESUME)
    public void onNtResume(Object... argv) {
        if (mBookInfo != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
            NotificationCenter.shared().postNotice(NTConfig.NT_CHANGE_MEDIA_INFO, 1);
            startCalcTime();
        } else {
            Toast.makeText(this, R.string.s_choice_book, Toast.LENGTH_SHORT).show();
        }
    }

    @Notice(NTConfig.NT_MD_NEXT)
    public void onNtNext(Object... argv) {
        mIsPrepare = false;
        if (mBookInfo != null) {
            mCurrentIndex++;
            // check is local
            String url;
            if (mBookInfo.containsKey(LrtsConfig.K_DOWNDLOAD) && mBookInfo.getJSONArray(LrtsConfig.K_DOWNDLOAD).contains(mCurrentIndex)) {
                String path = Environment.getExternalStoragePublicDirectory(AppConfig.SD_BOOK).getPath();
                String name = mBookInfo.getStringValue(LrtsConfig.K_NAME);
                url = String.format("%s/%s/%s.mp3", path, name, mCurrentIndex);
            } else {
                url = mBookInfo.getJSONObject(LrtsConfig.K_CHAPTER_LIST).getStringValue(mCurrentIndex.toString());
            }
            System.out.println(url);
            try {
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(this, Uri.parse(url));
                mMediaPlayer.prepareAsync();
            } catch (Exception e) {
                e.printStackTrace();
            }
            NotificationCenter.shared().postNotice(NTConfig.NT_CHANGE_MEDIA_INFO, 0, mBookInfo, mCurrentIndex);
        } else {
            Toast.makeText(this, R.string.s_choice_book, Toast.LENGTH_SHORT).show();
        }
    }

    public boolean isPlay() {
        return mMediaPlayer.isPlaying();
    }

    private void startCalcTime() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mIsPrepare) {
                    mBookInfo.put(LrtsConfig.K_CUR_CHAPTER, mCurrentIndex);
                    mBookInfo.put(LrtsConfig.K_CUR_POS, mMediaPlayer.getCurrentPosition());
                    NotificationCenter.shared().postNotice(NTConfig.NT_CHANGE_PROG, mMediaPlayer.getCurrentPosition(), mMediaPlayer.getDuration());
                }
            }
        }, 0, 1000);
    }

    @Override
    public void onPrepared(final MediaPlayer mp) {
        mIsPrepare = true;
        mp.start();
        if (mPos != 0 && mPos < mp.getDuration()) {
            mp.seekTo(mPos);
            mPos = 0;
        }
    }


    public void onCompletion(MediaPlayer mp) {
        Toast.makeText(this, R.string.s_jump_next, Toast.LENGTH_SHORT).show();
        NotificationCenter.shared().postNotice(NTConfig.NT_MD_NEXT);
    }
}
